/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow strict-local
 */

import React from 'react';
import {
  SafeAreaView,
  FlatList,
  StatusBar,
  ActivityIndicator,
  StyleSheet,
  View,
  Text
} from 'react-native';
import axios from 'axios';

const REQUEST_URL = 'https://api.github.com/search/repositories?q=javascript&sort=stars&page=';
let pageNo = 1;//当前第几页
let totalPage=5;//总的页数
let itemNo=0;//item的个数


class AppRefresh extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      error: false,
      errorInfo: "",
      dataArray:[],
      showFoot:0,
      isRefreshing: false
    }
  }

  componentDidMount() {
    this.fetchData(0);
  }


  fetchData = (pageNo) => {
    let currentDatas = this.state.dataArray;
    axios.get(REQUEST_URL + pageNo).then((response) => {
      console.log(response);
      let data = response.data.items;
      let dataBlob = [];
      let i = itemNo;
      data.map((item) => {
        dataBlob.push({
          key: i,
          value: item,
        })
        i++;
      })
      itemNo = i;
      let foot = 0;
      if (pageNo >= totalPage) {
        foot = 1;
      }
      if(pageNo == 1) {
        currentDatas = dataBlob;
      } else {
        currentDatas = currentDatas.concat(dataBlob)
      }
      this.setState({
        dataArray: currentDatas,
        isLoading: false,
        showFoot: foot,
        isRefreshing: false,
      })  
    }).catch(function (error) {
      console.log(error);
      this.setState({
        error: true,
        errorInfo: error
      })
    })
  }

  renderLoadingView = () => {
    return (
      <View style={styles.container}>
        <ActivityIndicator
          animating={true}
          color='red'
          size="large"
        />
      </View>
    );
  }

  //加载失败view
  renderErrorView = () => {
    return (
      <View style={styles.container}>
        <Text>
          Fail
            </Text>
      </View>
    );
  }

  //返回itemView
  renderItemView = ({ item }) => {
    return (
      <View>
        <Text style={styles.title}>name: {item.value.name}</Text>
        <Text style={styles.content}>stars: {item.value.stargazers_count}</Text>
        <Text style={styles.content}>description: {item.value.description}</Text>
      </View>
    );
  }

  renderData = () => {
    return (
      <>
      <StatusBar barStyle="dark-content" />
      <SafeAreaView />
      <FlatList
        refreshing={this.state.isRefreshing}
        onRefresh={this.refresh}
        data={this.state.dataArray}
        renderItem={this.renderItemView}
        ListFooterComponent={this.renderFooter.bind(this)}
        onEndReached={this.onEndReached.bind(this)}
        onEndReachedThreshold={0.1}
        ItemSeparatorComponent={this.separator}
      />
      <SafeAreaView />
      </>
    );
  }

  refresh = () => {
    pageNo = 1;
    itemNo = 0;
    this.setState({isRefreshing:true})
    this.fetchData(pageNo);
  }

  render() {
    console.log("render()");
    //第一次加载等待的view
    if (this.state.isLoading && !this.state.error) {
      return this.renderLoadingView();
    } else if (this.state.error) {
      //请求失败view
      return this.renderErrorView();
    }
    //加载数据
    return this.renderData();
  }

  separator = () => {
    return <View style={{ height: 1, backgroundColor: '#999999' }} />;
  }

  renderFooter () {
    console.log("renderFooter showFoot", this.state.showFoot);
    if (this.state.showFoot === 1) {
      return (
        <View style={{ height: 30, alignItems: 'center', justifyContent: 'flex-start', }}>
          <Text style={{ color: '#999999', fontSize: 14, marginTop: 5, marginBottom: 5,}}>
            没有更多数据了
          </Text>
        </View>
      )
    } else if (this.state.showFoot === 2) {
      return (
        <View style={styles.footer}>
          <ActivityIndicator />
          <Text>正在加载更多数据...</Text>
        </View>
      )
    } else if (this.state.showFoot === 0) {
      return (
        <View style={styles.footer}>
          <Text></Text>
        </View>
      );
    }
  }

  onEndReached () {
    console.log("onEndReached", this.state.showFoot);
    if (this.state.showFoot != 0) {
      return;
    }

    if ((pageNo != 1) && (pageNo >= totalPage)) {
      return;
    } else {
      pageNo++;
    }
    this.setState({ showFoot: 2 });
    this.fetchData(pageNo);
  }
}

class ActivityIndicatorDemo extends React.Component {
  render() {
      return (
          <View style={styles.container}>
              <ActivityIndicator
                  animating={true}
                  color='red'
                  size="large"
              />
          </View>
      );
  }
}

const styles = StyleSheet.create({
  container: {
      flex: 1,
      flexDirection: 'row',
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: '#F5FCFF',
  },
  title: {
      fontSize: 15,
      color: 'blue',
  },
  footer:{
      flexDirection:'row',
      height:24,
      justifyContent:'center',
      alignItems:'center',
      marginBottom:10,
  },
  content: {
      fontSize: 15,
      color: 'black',
  }
});

export default AppRefresh;
